package net.caixiaomi.info.shopkeeper;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.ArticleAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.OrderRecordModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.shopkeeper.adapter.ShopOrderAdapter;
import net.caixiaomi.info.shopkeeper.entity.ShopDetailEntity;
import net.caixiaomi.info.shopkeeper.entity.ShopDetailMainEntity;
import net.caixiaomi.info.shopkeeper.entity.ShopHistoryDetailEntity;
import net.caixiaomi.info.shopkeeper.entity.ShopMainEntity;
import net.caixiaomi.info.shopkeeper.entity.ShopOrderEntity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * Created by mac on 2018/11/19.
 */

public class ShopOrderHistoryActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener, OnRefreshListener,View.OnClickListener{

    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;
    @BindView(android.R.id.list)
    RecyclerView mListView;
    ShopPhotoDialog dialog;
    @BindView(R.id.progress)
    CircularProgressBar mProgress;
    @BindView(R.id.shop_timer_tv)
    TextView mTimerTv;
    @BindView(R.id.shop_timer_group)
    LinearLayout mTimerLayout;

    @BindView(R.id.shop_timer_des0)
    TextView mDesTv0;
    @BindView(R.id.shop_timer_des1)
    TextView mDesTv1;
    @BindView(R.id.shop_timer_des2)
    TextView mDesTv2;

    @OnClick(R.id.shop_timer_group)
    void matchingDate(){
        pvTime.show(mTimerLayout);
    }

    private List<ShopOrderEntity> mList;
    private ShopOrderAdapter mAdapter;
    private String mCurrentTime = "";
    private TimePickerView pvTime;

    private int mPageNum = 1;
    private int mPageSize=20;

    private boolean isShowing=false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mList=new ArrayList<>();
        initView();
        initData();
        mProgress.setVisibility(View.VISIBLE);
    }

    private void initView(){
        mListView.setLayoutManager(new LinearLayoutManager(this));
        mRefresh.setOnRefreshListener(this);
        mAdapter = new ShopOrderAdapter(null);
        mAdapter.setType(1);
        mAdapter.setOnItemClickListener(this);
        mListView.setAdapter(mAdapter);
        mAdapter.setOnLoadMoreListener(this, mListView);
        mAdapter.setEnableLoadMore(true);

        initTimePicker();
        Date date=new Date();
//        String token= CommonApp.getToken();
        mCurrentTime=getTime(date);
        mTimerTv.setText(mCurrentTime);
    }

    private void initData(){
        JSONObject params = new JSONObject();
        String[]times=mCurrentTime.split("-");
        if(times[1].startsWith("0")){
            String month=times[1].replace("0","");
            times[1]=month;
        }
        if(times[2].startsWith("0")){
            String day=times[2].replace("0","");
            times[2]=day;
        }
        mCurrentTime=times[0]+"-"+times[1]+"-"+times[2];

        params.put("dateStr",mCurrentTime);
        params.put("pageNum", mPageNum);
        params.put("pageSize", mPageSize);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<ShopMainEntity>> baseCallModelCall = requestService.queryLogXN(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<ShopMainEntity>>() {
            @Override
            public void onSuccess(BaseCallModel<ShopMainEntity> data) {
                mTimerTv.setText(mCurrentTime);
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                ShopMainEntity entity=data.data;
                mDesTv0.setText("出票成功: "+entity.getSucNum());
                mDesTv1.setText("出票失败: "+entity.getFailNum());
                mDesTv2.setText("总订单额: "+entity.getSucMoney()+"元");
                List<ShopOrderEntity>list=data.data.getPrintRecord().getList();

                if (list != null && !list.isEmpty()) {
                    if (mPageNum == 1) {
                        mAdapter.getData().clear();
                    }
                    mAdapter.addData(list);
                    mAdapter.loadMoreComplete();
                    mAdapter.notifyDataSetChanged();
                    mAdapter.setEnableLoadMore(Boolean.valueOf(data.data.getPrintRecord().getHasNextPage()));
                }
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                if (mPageNum != 1) {
                    mAdapter.loadMoreComplete();
                }
                mPageNum = mAdapter.getData().size() % Integer.valueOf(Constants.PAGE_SIZE) == 0 ? mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) : mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) + 1;

            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                if (mPageNum != 1) {
                    mAdapter.loadMoreComplete();
                }
                mPageNum = mAdapter.getData().size() % Integer.valueOf(Constants.PAGE_SIZE) == 0 ? mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) : mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) + 1;

            }
        });
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    protected int layout() {
        return R.layout.shop_order_history_layout;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if(isShowing){
            return;
        }
        try {
            mProgress.setVisibility(View.VISIBLE);
        isShowing=true;
        ShopOrderEntity item= (ShopOrderEntity) adapter.getData().get(position);
        JSONObject params = new JSONObject();
        params.put("orderSn", item.getOrderSn());
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<ShopHistoryDetailEntity>> baseCallModelCall = requestService.queryLogDetailXN(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<ShopHistoryDetailEntity>>() {
            @Override
            public void onSuccess(BaseCallModel<ShopHistoryDetailEntity> data) {

                mProgress.setVisibility(View.GONE);
                dialog=new ShopPhotoDialog(ShopOrderHistoryActivity.this, new ShopPhotoDialog.callBack() {
                    @Override
                    public void setPhoto(Intent intent, int requestCode) {

                    }

                    @Override
                    public void success() {
                        initData();
                    }

                    @Override
                    public void failure() {
                        initData();
                    }
                });
                ShopDetailEntity entity=new ShopDetailEntity();
                entity.setOrderDetailDto(data.data.getOrderDetailDto());
                entity.setTicketSchemeDTO(data.data.getTicketSchemeDTO());

                ShopDetailMainEntity main=new ShopDetailMainEntity();
                main.setDetail(entity);
                main.setPhotpee(data.data.getTicketPicDTO());
                main.setShopStatus(1);  //完成状态

                dialog.setShopEntity(main);
                dialog.show();
                dialog.setCancelable(true);
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        isShowing=false;
                    }
                });
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                isShowing=false;
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
                isShowing=false;
            }
        });
        }catch (Exception e){
            mProgress.setVisibility(View.GONE);
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private void initTimePicker() {//Dialog 模式下，在底部弹出

        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
//                Toast.makeText(OpenPrizeFootballAcitivity.this, getTime(date), Toast.LENGTH_SHORT).show();
                mCurrentTime=getTime(date);
//                mTimerTv.setText(mCurrentTime);
                mPageNum = 1;
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
                initData();
                Log.i("pvTime", "onTimeSelect");

            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                        Log.i("pvTime", "onTimeSelectChanged");
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPageNum = 1;
        initData();
    }

    @Override
    public void onLoadMoreRequested() {
        mPageNum++;
        initData();
    }
}
